console.log("初始化");
/****初始化app****/
var myApp = new Framework7({
    modalTitle: '哇吖·城市探秘',
    modalButtonOk: '知道了',
    animateNavBackIcon: true,
    precompileTemplates: true,
    template7Pages: true,
});

//初始化view 
var mainView = myApp.addView('.view-main', {
	  dynamicNavbar: true
});

//开启loader
myApp.showIndicator();

// Export selectors engine
var $$ = Dom7;
var url_init_wx_jsapi = "http://api.wayatrip.com/weixinapi/init_wx_jsapi";
var url_get_wx_device_params = "http://api.wayatrip.com/treasurehunter/get_wx_device_params";
var url_post_wx_deivce_qb = "http://api.wayatrip.com/treasurehunter/get_wx_device_qb";

//预编译模板
myApp.qblistItemTemplate = Template7.compile($$('script#qblist_item').html());

/****获取微信设备参数****/

var devices = [];
$$.ajax({
	url:url_get_wx_device_params,
    method:"GET",
    data: {},
    dataType:'json',
    success: function (ajaxresult) {
    	if(ajaxresult.code==1){
    		var res=ajaxresult.data;
    		var i;
    		for(i in res){
    			//结合major和minor生成targetid
    			var majorstr = res[i]['major'];
			    majorstr = majorstr.toString();
			    var minorstr = res[i]['minor'];
				minorstr = minorstr.toString();
			    var targetid = majorstr+minorstr;
			    
    			devices[targetid] = res[i];
    		}
    	    //console.log(devices);
        }else{
            console.log(ajaxresult.msg);
        }
    }
});

/****微信js sdk初始化****/
var WXsignature,WXappid,WXnonceStr,WXtimestamp;
var jsapilist = ['startSearchBeacons','stopSearchBeacons','onSearchBeacons'];
var $$ = Dom7;

//请求权限申请参数
$$.ajax({
	url:url_init_wx_jsapi,
    method:"GET",
    data: {from_url:window.location.href},
    dataType:'json',
    async:false,
    success: function (ajaxresult) {    	
    	if(ajaxresult.code==1){
    		var res=ajaxresult.data;
    		WXsignature = res.signature;
    		WXappid = res.appid;
    		WXnonceStr = res.nonceStr;
    		WXtimestamp = res.timestamp;
        }else{
            console.log(ajaxresult.msg);
        }
    }
});

//权限申请
wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: WXappid, // 必填，公众号的唯一标识
    timestamp: WXtimestamp, // 必填，生成签名的时间戳
    nonceStr: WXnonceStr, // 必填，生成签名的随机串
    signature: WXsignature,// 必填，签名，见附录1
    jsApiList: jsapilist // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
});

//权限通过调用
wx.ready(function(){
	//检测js接口是否可用
	wx.checkJsApi({
	    jsApiList: jsapilist, 
	    success: function(res) {
	        // 以键值对的形式返回，可用的api值true，不可用为false
	        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
	        var i;
	        var result = res.checkResult;
	        for(i in result){
	        	//console.log(i+"=>"+result[i]);
	        }
	    }
	});
	
	//点击开始搜索，开始监听周边ibeacon
	$$('#radar_index .scan-btn.start').click(function(){
		//打开接口
		wx.startSearchBeacons({
			  ticket:"",//非必须，摇周边的业务ticket，系统自动添加在摇出来的页面链接后面  
			  complete:function(argv){
				 //蓝牙是否打开
				 var bluetooth = true;
				 //微信位置服务是否打开
				 var locservice = true;
				 //微信系统是否支持接口
				 var syssupport = true;
				 
				 var rescode = argv.errMsg;
				 var rescode =rescode.toString();
	             
	             if(rescode.indexOf('bluetooth') != -1){
	            	 myApp.alert('请打开手机的蓝牙');
	            	 bluetooth = false;
	             }else if(rescode.indexOf('location') != -1){
	            	 myApp.alert('请打开微信的位置服务');
	            	 locservice = false;
	             }else if(rescode.indexOf('system') != -1){
	            	 myApp.alert('当前微信版本不支持该功能');
	            	 syssupport = false;
	             }else{
	            	 
	             }
	             
	             if(!bluetooth || !locservice || !syssupport){
	            	 //关闭搜索
	            	 wx.stopSearchBeacons({
		       			  complete:function(res){
		       				 //雷达指针停止旋转
		    				 $$('#radar_index .pointer').removeClass('pointAnimation');
		    				 $$('#radar_index .scan-btn.stop').hide();
		    				 $$('#radar_index .scan-btn.start').show();
		       			  }
	       		     });
	            	 return;
	             }
	             
	             //雷达指针旋转
	             $$('#radar_index .pointer').addClass('pointAnimation');
	         	 $$('#radar_index .scan-btn.start').hide();
	         	 $$('#radar_index .scan-btn.stop').show();
	         	 
	             //绑定监听事件
	             wx.onSearchBeacons({
		   			  complete:function(argv){
		   				  var i;
		   				  var targets = '';
		   				  var beacons = argv.beacons;
		   				  
		   				  for(i in beacons){
		   					  //结合major和minor生成targetid
		   					  var majorstr = beacons[i]['major'];
		   					  majorstr = majorstr.toString();
		   					  var minorstr = beacons[i]['minor'];
		   					  minorstr = minorstr.toString();
		   					  var targetid = majorstr+minorstr;
		   					  
		   					  targets += "<span class='targetloc' "
		   						  +"data-targetid='"+targetid+"' "
		   						  +"data-rssi='"+beacons[i]['rssi']+"' "
		   						  +"data-uuid='"+beacons[i]['uuid']+"' "
		   						  +"data-major='"+beacons[i]['major']+"' "
		   						  +"data-minor='"+beacons[i]['minor']+"'></span>";
		   					  //myApp.alert(targetid);
		   				      /*myApp.alert('rssi:'+beacons[i]['rssi']+'<br>'
				   						  +'uuid:'+beacons[i]['uuid']+'<br>'
				   						  +'major:'+beacons[i]['major']+'<br>'
				   						  +'minor:'+beacons[i]['minor']);*/
		   				  }
		   				  //刷新目标
		   				  $$('#radar_index .target').html(targets);
		   				  refreshRadar();
		   			  }
	   		     });
	             //PC端测试
	             //refreshRadar();
			  }
		});
		
	});
	//关闭搜索ibeacon
	$$('#radar_index .scan-btn.stop').click(function(){
		wx.stopSearchBeacons({
			  complete:function(res){
				  //雷达指针停止旋转
				  $$('#radar_index .pointer').removeClass('pointAnimation');
				  $$('#radar_index .scan-btn.stop').hide();
				  $$('#radar_index .scan-btn.start').show();
			  }
		});
	});
	//关闭loader
	myApp.hideIndicator();
});

//权限失败调用
wx.error(function(res){
	myApp.alert('微信js sdk调用失败');
});